package metaballs;

import java.util.LinkedList;
import java.util.Random;

import util.Vec2F;

public class MetaballClump
{
	private final LinkedList<Metaball> metaballs;
	private Vec2F center;
	private float radius;
	private float minForce,maxForce;
	public MetaballClump(Vec2F center,float radius,float minForce,float maxForce)
	{
		metaballs = new LinkedList<Metaball>();
		this.center = center;
		this.radius = radius;
		this.minForce = minForce;
		this.maxForce = maxForce;
		
	}
	public void initializeStableClump(int numBalls)
	{
		Random random = new Random();
		Metaball metaball;
		for(int i=0;i<numBalls;i++)
		{
			float randomAngle = random.nextFloat() * 2 * (float)Math.PI;
			float randomRadius = random.nextFloat() * radius;
			metaball = new Metaball(center.add(new Vec2F((float)Math.cos(randomAngle) * randomRadius,(float)Math.sin(randomAngle) * randomRadius)),
									new Vec2F(128,128), 
									0.0f, 1.0f);
			add(metaball);
		}
	}
	
	public void add(Metaball metaball)
	{
		metaballs.add(metaball);
	}
	public void add(LinkedList<Metaball> newMetaballs)
	{
		metaballs.addAll(newMetaballs);
	}	
	public void applyForces()
	{
		for(Metaball metaball: metaballs)
		{
			Vec2F displacementVector = metaball.getLocation().sub(center);
			float displacement = displacementVector.mag();
			float force;
			if(displacement > radius)
				displacement = radius;
			
			force = minForce + (maxForce - minForce) * (radius - displacement)/radius;
			metaball.accumulateAcceleration(displacementVector.scale(-force/displacement));
		}
	}
	public LinkedList<Metaball> getMetaballs()
	{
		return metaballs;
	}
	public Vec2F getCenter()
	{
		return center;
	}
	public void setCenter(Vec2F center)
	{
		this.center = center;
	}
	public float getRadius()
	{
		return radius;
	}
	public void setRadius(float radius)
	{
		this.radius = radius;
	}
}
